package com.quanshu.exchange.ui.gui.web_page;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.MyOrderEntity;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.exchange.ui.gui.pay.AlipayActivity;
import com.quanshu.exchange.ui.gui.profile.AllOrderActivity;
import com.quanshu.exchange.ui.gui.profile.DeliveryAddressActivity;
import com.quanshu.exchange.wxapi.WXPayEntryActivity;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 待付款进来 --  订单结算
 * Created by xiniu003 on 2018/1/24.
 */

public class OrderPaymentActivity extends BaseActivity {

    @BindView(R.id.settle_order_payment)
    WebView mWebview;
    WebSettings mWebSettings;
    @BindView(R.id.back_llt)
    LinearLayout backLlt;

    private MyOrderEntity myOrderEntity;
    private String indexUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_payment);
        ButterKnife.bind(this);

        getIntentData();

        initView();
        initEvent();
    }

    private void initEvent() {
        RxViewHelper.getInstance().clicks(backLlt, aVoid -> {
            finish();
        });
    }

    private void getIntentData() {
        Intent intent = getIntent();
        myOrderEntity = (MyOrderEntity) intent.getSerializableExtra("myOrderEntity");
    }

    private void initView() {
        String CTMD_Id = null;

        if (myOrderEntity.getGoods_type().equals("goods")) {

            CTMD_Id = myOrderEntity.getGoods_id();

        } else {

            CTMD_Id = myOrderEntity.getProduct_id();
        }

        indexUrl = Config.URL_HOST_SHOP +
                Config.create_orderPayment_id + CTMD_Id +
                Config.create_orderPayment_num + myOrderEntity.getGoods_nums() +
                Config.create_orderPayment_type + myOrderEntity.getGoods_type() +
                Config.create_orderPayment_isService + myOrderEntity.getIs_service() +
                Config.is_inn + myOrderEntity.getIs_inn() +
                Config.create_orderPayment_userId + String.valueOf(MyApplication.getInstance().getCurrentUser().getId()) +
                Config.create_orderPayment_memberid + MyApplication.getInstance().getCurrentUser().getMemberid() +
                Config.create_orderPayment_orderId + myOrderEntity.getOid() +
                Config.create_orderPayment_fromOrder + "/payment_options/" + myOrderEntity.getPayment_options();

        mWebSettings = mWebview.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setDefaultTextEncodingName("UTF-8");
        mWebSettings.setTextSize(WebSettings.TextSize.NORMAL);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebview.setWebChromeClient(new WebChromeClient());
        mWebview.setWebViewClient(new MyWebViewClient());
        mWebview.loadUrl(indexUrl);
    }

    /**
     * http://test.cattleshop.cn/
     * cattle_exchange_simple/cart2/id/69
     * /num/1
     * /type/product
     * /is_service/1
     * /user_id/11716
     * /memberid/marco
     * /from/order
     */

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains("index/login/1")) {
                Intent intent = new Intent(OrderPaymentActivity.this, LoginActivity.class);
                startActivity(intent);
                return true;
            }
            if (url.contains("address/add") || url.contains("error")) {
                backLlt.setVisibility(View.VISIBLE);
            } else {
                backLlt.setVisibility(View.GONE);
            }
            try {
                if (url.equals(Config.skip_colsePayment) ||
                        url.equals(Config.skip_weixinPay_back)) {//返回上一页处理

                    finish();
                } else if (url.contains("address/add")) {//结算时，若无收货地址。当走此路径
                    Intent intent = new Intent(OrderPaymentActivity.this, DeliveryAddressActivity.class);
                    intent.putExtra("FLAG", "flag");
                    startActivityForResult(intent, 12);
                } else if (url.equals(Config.URL_HOST_SHOP)) {//在微信或支付宝支付页返回

                    Intent intent = new Intent(OrderPaymentActivity.this, AllOrderActivity.class);
                    startActivity(intent);

                } else if (!url.equals(Config.URL_HOST_SHOP)) {

                    if (url.contains("goApp?or")) {//牛积分支付成功路径
                        Intent intent = new Intent(OrderPaymentActivity.this, AllOrderActivity.class);
                        startActivity(intent);
                    } else if (url.contains("products") || url.contains("e/cart2/")) {
                        view.loadUrl(url);
                        return false;
                    } else if (url.contains("goApp?wx")) {//前往微信
                        doWxPay(url);
                        view.loadUrl(indexUrl);
                        return true;
                    } else if (url.contains("goApp?al")) { //前往支付宝
                        doAliPay(url);
                        view.loadUrl(indexUrl);
                        return true;
                    } else {
                        return false;
                    }
                } else {

                    return false;
                }
            } catch (Exception e) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
            }
            return true;
        }
    }

    private void doWxPay(String url) {
        Intent intent = new Intent(OrderPaymentActivity.this, WXPayEntryActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    private void doAliPay(String url) {
        Intent intent = new Intent(OrderPaymentActivity.this, AlipayActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 12) {
                finish();
            }
        }
    }
}
